package com.richard.library.basic.util;

import android.os.Build;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.SparseLongArray;

import androidx.annotation.RequiresApi;
import androidx.collection.ArrayMap;
import androidx.collection.LongSparseArray;
import androidx.collection.SimpleArrayMap;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2017/12/24
 *     desc  : utils about object
 * </pre>
 */
public final class ObjectUtil {

    private ObjectUtil() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * Return whether object is empty.
     *
     * @param obj The object.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isEmpty(final Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
            return true;
        }
        if (obj instanceof CharSequence && obj.toString().length() == 0) {
            return true;
        }
        if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof Map && ((Map) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof SimpleArrayMap && ((SimpleArrayMap) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof SparseArray && ((SparseArray) obj).size() == 0) {
            return true;
        }
        if (obj instanceof SparseBooleanArray && ((SparseBooleanArray) obj).size() == 0) {
            return true;
        }
        if (obj instanceof SparseIntArray && ((SparseIntArray) obj).size() == 0) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (obj instanceof SparseLongArray && ((SparseLongArray) obj).size() == 0) {
                return true;
            }
        }
        if (obj instanceof LongSparseArray && ((LongSparseArray) obj).size() == 0) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (obj instanceof android.util.LongSparseArray
                    && ((android.util.LongSparseArray) obj).size() == 0) {
                return true;
            }
        }
        return false;
    }

    public static boolean isEmpty(final CharSequence obj) {
        return obj == null || obj.toString().length() == 0;
    }

    public static boolean isEmpty(final Collection obj) {
        return obj == null || obj.isEmpty();
    }

    public static boolean isEmpty(final Map obj) {
        return obj == null || obj.isEmpty();
    }

    public static boolean isEmpty(final SimpleArrayMap obj) {
        return obj == null || obj.isEmpty();
    }

    public static boolean isEmpty(final SparseArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final SparseBooleanArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final SparseIntArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final LongSparseArray obj) {
        return obj == null || obj.size() == 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static boolean isEmpty(final SparseLongArray obj) {
        return obj == null || obj.size() == 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static boolean isEmpty(final android.util.LongSparseArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final ArrayMap obj) {
        return obj == null || obj.isEmpty();
    }

    /**
     * Return whether object is not empty.
     *
     * @param obj The object.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isNotEmpty(final Object obj) {
        return !isEmpty(obj);
    }


    public static boolean isNotEmpty(final CharSequence obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final Collection obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final Map obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SimpleArrayMap obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SparseArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SparseBooleanArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SparseIntArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final LongSparseArray obj) {
        return !isEmpty(obj);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static boolean isNotEmpty(final SparseLongArray obj) {
        return !isEmpty(obj);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static boolean isNotEmpty(final android.util.LongSparseArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final ArrayMap obj) {
        return !isEmpty(obj);
    }

    public static boolean isNullOr(Object... obj) {
        for (Object o : obj) {
            if (o == null) {
                return true;
            }
        }
        return false;
    }

    public static boolean isNullAnd(Object... obj) {
        for (Object o : obj) {
            if (o != null) {
                return false;
            }
        }
        return true;
    }

    public static boolean isEmptyOr(Object... obj) {
        for (Object o : obj) {
            if (isEmpty(o)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isEmptyAnd(Object... obj) {
        for (Object o : obj) {
            if (isNotEmpty(o)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断两个对象是否相等
     */
    public static boolean eq(final Object o1, final Object o2) {
        return o1 != null && o1.equals(o2);
    }

    /**
     * 判断两个数值对象是否相等
     */
    public static boolean eqNum(final Object o1, final Object o2) {
        return o1 != null && toDouble(o1) == toDouble(o2);
    }

    /**
     * Require the objects are not null.
     *
     * @param objects The object.
     * @throws NullPointerException if any object is null in objects
     */
    public static void requireNonNull(final Object... objects) {
        if (objects == null) throw new NullPointerException();
        for (Object object : objects) {
            if (object == null) throw new NullPointerException();
        }
    }

    /**
     * Return the nonnull object or default object.
     *
     * @param object        The object.
     * @param defaultObject The default object to use with the object is null.
     * @param <T>           The value type.
     * @return the nonnull object or default object
     */
    public static <T> T getOrDefault(final T object, final T defaultObject) {
        if (object == null) {
            return defaultObject;
        }
        return object;
    }


    /**
     * 获取字符串（若字符串为""或者null，则返回指定默认值，否则返回value）
     *
     * @param value        原值
     * @param defaultValue 默认值
     */
    public static String getValueOrDefault(final String value, final String defaultValue) {
        if (isEmpty(value)) {
            return defaultValue;
        }
        return value;
    }

    /**
     * 获取列表第一个元素
     */
    public static <T> T getListFirst(List<T> list) {
        if (isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * Return the hash code of object.
     *
     * @param o The object.
     * @return the hash code of object
     */
    public static int hashCode(final Object o) {
        return o != null ? o.hashCode() : 0;
    }

    /**
     * obj满足等于match中任意一个元素则返回true
     */
    public static boolean orEq(Object obj, Object... match) {
        if (obj == null) {
            return false;
        }
        for (Object item : match) {
            if (eq(obj, item)) {
                return true;
            }
        }

        return false;
    }

    /**
     * obj满足等于match中全部元素则返回true
     */
    public static boolean andEq(Object obj, Object... match) {
        if (obj == null) {
            return false;
        }
        for (Object item : match) {
            if (!eq(obj, item)) {
                return false;
            }
        }

        return true;
    }

    /****************************************以下为类型类型转换相关************************************/

    public static <T> T toT(Object obj) {
        return obj == null ? null : (T) obj;
    }

    public static String toString(Object obj) {
        return toString(obj, "");
    }

    public static String toString(Object obj, String devVal) {
        return obj == null ? devVal : String.valueOf(obj);
    }

    public static boolean toBoolean(Object obj) {
        return toBoolean(obj, false);
    }

    public static boolean toBoolean(Object obj, boolean defVal) {
        try {
            if (obj == null) {
                return defVal;
            }

            if (obj.getClass().isAssignableFrom(boolean.class) || obj.getClass().isAssignableFrom(Boolean.class)) {
                return (boolean) obj;
            }

            return Boolean.parseBoolean(toString(obj));
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public static double toDouble(Object obj) {
        return toDouble(obj, 0D);
    }

    public static double toDouble(Object obj, double defVal) {
        try {
            if (isEmpty(obj)) {
                return defVal;
            }

            if (obj.getClass().isAssignableFrom(double.class) || obj.getClass().isAssignableFrom(Double.class)) {
                return (double) obj;
            }

            return Double.parseDouble(toString(obj));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return defVal;
    }

    public static float toFloat(Object obj) {
        return toFloat(obj, 0F);
    }

    public static float toFloat(Object obj, float defVal) {
        try {
            if (isEmpty(obj)) {
                return defVal;
            }

            if (obj.getClass().isAssignableFrom(float.class) || obj.getClass().isAssignableFrom(Float.class)) {
                return (float) obj;
            }

            return (float) toDouble(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return defVal;
    }

    public static int toInt(Object obj) {
        return toInt(obj, 0);
    }

    public static int toInt(Object obj, int defVal) {
        try {
            if (isEmpty(obj)) {
                return defVal;
            }

            if (obj.getClass().isAssignableFrom(int.class) || obj.getClass().isAssignableFrom(Integer.class)) {
                return (int) obj;
            }

            return (int) toDouble(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return defVal;
    }

    public static long toLong(Object obj) {
        return toLong(obj, 0L);
    }

    public static long toLong(Object obj, long defVal) {
        try {
            if (isEmpty(obj)) {
                return defVal;
            }

            if (obj.getClass().isAssignableFrom(long.class) || obj.getClass().isAssignableFrom(Long.class)) {
                return (int) obj;
            }

            return (long) toDouble(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return defVal;
    }

    /****************************************以下为对象克隆相关***************************************/


    /**
     * Deep clone.
     *
     * @param data The data.
     * @param <T>  The value type.
     * @return The object of cloned
     */
    public static <T> T deepClone(final Serializable data) {
        if (data == null) return null;
        return (T) bytes2Object(serializable2Bytes((Serializable) data));
    }

    private static byte[] serializable2Bytes(final Serializable serializable) {
        if (serializable == null) return null;
        ByteArrayOutputStream baos;
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos = new ByteArrayOutputStream());
            oos.writeObject(serializable);
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static Object bytes2Object(final byte[] bytes) {
        if (bytes == null) return null;
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}